﻿namespace EFS.RC.CCAdmin.Customers
{
	public partial class Edit : EFS.RC.CCAdmin.Common.Control
	{
		private EFS.RC.CC.Deployment.Entities.EndPoints.Office[] offices = null;
		private EFS.RC.CC.Deployment.Entities.Skill[] skills = null;
		private EFS.Common.UI.Controls.ModalDialogHost host = null;
		private EFS.RC.CC.Deployment.Views.EndPoints.CustomerDetails customer;

		#region Constructor

		public Edit()
		{
			InitializeComponent();

			if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
			{
				RegisterListeners();
				this.Loaded += new System.Windows.RoutedEventHandler(Edit_Loaded);
			}
		}

		public Edit(EFS.Common.UI.Controls.ModalDialogHost host, EFS.RC.CC.Deployment.Views.EndPoints.CustomerDetails customer)
		{
			InitializeComponent();

			// set customer
			this.customer = customer;
			this.host = host;

			//set listener up for list load
			UtilitiesService.Classifications_GetByLineIdCompleted += new System.EventHandler<WebProxy.Classifications_GetByLineIdCompletedEventArgs>(UtilitiesService_Classifications_GetByLineIdCompleted);


			//set delete response listener
			UtilitiesService.Classification_DeleteCompleted += new System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(UtilitiesService_Classification_DeleteCompleted);
			
			// register ok click
			host.OnButtonOKClick += SavePhone;

			// register 
			if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
			{
				RegisterListeners();
				this.Loaded += new System.Windows.RoutedEventHandler(Edit_Loaded);
			}
		}

		#endregion

		#region Service Events

		private void RegisterListeners()
		{
			//skills
			UtilitiesService.Skills_GetAllCompleted += new System.EventHandler<WebProxy.Skills_GetAllCompletedEventArgs>(UtilitiesService_Skills_GetAllCompleted);

			//offices
			UtilitiesService.OfficeEndPoints_GetAllCompleted += new System.EventHandler<WebProxy.OfficeEndPoints_GetAllCompletedEventArgs>(UtilitiesService_OfficeEndPoints_GetAllCompleted);

			//create
			UtilitiesService.CustomerEndPoint_CreateCompleted += new System.EventHandler<WebProxy.CustomerEndPoint_CreateCompletedEventArgs>(UtilitiesService_CustomerEndPoint_CreateCompleted);

			//update
			UtilitiesService.CustomerEndPoint_UpdateCompleted += new System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(UtilitiesService_CustomerEndPoint_UpdateCompleted);

		}

		void UtilitiesService_Skills_GetAllCompleted(object sender, WebProxy.Skills_GetAllCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				// show wait DLG
				EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

				// show error
				ShowErrorMessage("Failed to retrieve Skills. ", e.Error);

				// done
				return;
			}

			try 
			{
				// deserialize
				skills = EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.Deployment.Entities.Skill[]>(e.Result.ToString());
			
				// load offices now
				UtilitiesService.OfficeEndPoints_GetAllAsync();
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to load data. " + ex.Message);
			}
		}

		void UtilitiesService_OfficeEndPoints_GetAllCompleted(object sender, WebProxy.OfficeEndPoints_GetAllCompletedEventArgs e)
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			//check if request was successful
			if (null != e.Error)
			{
				// show error
				ShowErrorMessage("Failed to retrieve Offices. ", e.Error);

				// done
				return;
			}

			try 
			{
				// deserialize
				offices = EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.Deployment.Entities.EndPoints.Office[]>(e.Result.ToString());

				// all is loaded, display
				DisplayData();
			}
			catch (System.Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message);
			}
		}

		void UtilitiesService_CustomerEndPoint_CreateCompleted(object sender, WebProxy.CustomerEndPoint_CreateCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Failed run update. ", e.Error);
			}
			else
			{
				this.host.Close(EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok);
			}
		}

		void UtilitiesService_CustomerEndPoint_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Failed run update. ", e.Error);
			}
			else
			{
				this.host.Close(EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok);
			}
		}

		#endregion

		#region Content loading

		private void LoadData()
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.InProgress(this, "Please wait while retrieving data");

			if (this.customer != null)
			{
				textBoxTelephone.Text = customer.URI;
			}

			//skills
			UtilitiesService.Skills_GetAllAsync();

			LoadClassifications();
		}

		private void DisplayData()
		{
			//check if all data has been loaded
			if (offices == null || 	skills == null)
			{
				return;
			}

			//fill forms, bind, do the magic
			comboBoxSkill.ItemsSource = skills;
			comboBoxOffice.ItemsSource = offices;

			if (customer != null)
			{
				comboBoxOffice.SelectedValue = customer.OfficeEndPointID;
				comboBoxSkill.SelectedValue = customer.SkillID;
			}
		}

		#endregion

		#region Events

		/// <summary>
		/// Create phone
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		/// <param name="dialogResult"></param>
		void SavePhone(object sender, System.Windows.RoutedEventArgs e, System.Boolean dialogResult)
		{
			if (null == customer)
			{
				//ws call
				UtilitiesService.CustomerEndPoint_CreateAsync(
					textBoxTelephone.Text,
					(System.Int32)comboBoxSkill.SelectedValue,
					(System.Int32)comboBoxOffice.SelectedValue);
			}
			else
			{
				//ws call
				UtilitiesService.CustomerEndPoint_UpdateAsync(
						customer.ID.Value,
						textBoxTelephone.Text,
						(System.Int32)comboBoxSkill.SelectedValue,
						(System.Int32)comboBoxOffice.SelectedValue);
			}
		}

		void Edit_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			LoadData();
		}

		#endregion

		#region CRUD Click listeners

		//edit classification button click in datagrid
		private void EditLink_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			EFS.RC.CC.CH.Entities.Classification classification = (EFS.RC.CC.CH.Entities.Classification)dataGridClassifications.SelectedItem;

			EFS.Common.UI.Controls.ModalDialogHost wnd = new EFS.Common.UI.Controls.ModalDialogHost();
			wnd.HostedContent = new EFS.RC.CCAdmin.Classifications.Edit(wnd, classification.ID);
			wnd.Show(OnEditWindowClosed);
		}

		//delete button click in datagrid
		private void DeleteLink_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			if (System.Windows.Browser.HtmlPage.Window.Confirm("Permanently delete classification?"))
			{
				// show wait DLG
				EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.InProgress(this, "Please wait while deleting classification");

				EFS.RC.CC.CH.Entities.Classification classification = (EFS.RC.CC.CH.Entities.Classification)dataGridClassifications.SelectedItem;
				UtilitiesService.Classification_DeleteAsync(classification.ID.Value);
			}
		}

		#endregion

		#region Window callbacks
		//add new classification
		private void OnNewWindowClosed(EFS.Common.UI.Controls.ModalDialogHost host)
		{
			//x or cancel pressed
			if (host.DialogClosedReason != EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok)
			{
				return;
			}

			// load classifications
			LoadClassifications();
		}

		//update classification
		private void OnEditWindowClosed(EFS.Common.UI.Controls.ModalDialogHost host)
		{
			//x or cancel pressed
			if (host.DialogClosedReason != EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok)
			{
				return;
			}

			// load classifications
			LoadClassifications();
		}
		#endregion

		#region LoadData

		/// LoadClassifications
		private void LoadClassifications()
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.InProgress(this, "Please wait while retrieving data");

			// load 
			if (null != customer.ID)
			{
				//call ws
				UtilitiesService.Classifications_GetByLineIdAsync(customer.ID.Value);
			}
		}
		#endregion

		#region WS callbacks

		// get by line
		void UtilitiesService_Classifications_GetByLineIdCompleted(object sender, WebProxy.Classifications_GetByLineIdCompletedEventArgs e)
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			// check
			if (null != e.Error)
			{
				ShowErrorMessage("Failed to retrieve classifications.", e.Error);

				// done
				return;
			}

			// remove previous
			dataGridClassifications.ItemsSource = null;

			// check
			if (null == e.Result)
			{
				// done
				return;
			}

			try
			{
				// get
				EFS.RC.CC.CH.Entities.Classification[] classifications = EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.CH.Entities.Classification[]>(e.Result.ToString());

				// bind/fill form
				dataGridClassifications.ItemsSource = new System.Collections.Generic.List<CC.CH.Entities.Classification>(classifications);
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to retrieve data.", ex);
			}
		}

		/// Delete classification completed
		private void UtilitiesService_Classification_DeleteCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			if (null != e.Error)
			{
				ShowErrorMessage("Failed to delete classification.", e.Error);
			}
			else
			{
				LoadClassifications();
			}
		}
		#endregion

		private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			EFS.Common.UI.Controls.ModalDialogHost wnd = new EFS.Common.UI.Controls.ModalDialogHost();
			wnd.HostedContent = new EFS.RC.CCAdmin.Classifications.Edit(wnd, null);
			wnd.Show(OnNewWindowClosed);
		}
	}
}